'use client';

import React, { useMemo } from 'react';
import EChartBase from './EChartBase';
import { EChartsOption } from 'echarts';

export interface PieDataItem {
  name: string;
  value: number;
  itemStyle?: {
    color?: string;
  };
}

interface PieChartProps {
  title?: string;
  data: PieDataItem[];
  height?: string | number;
  doughnut?: boolean; // 是否为环形图
  radius?: string | string[] | number | number[]; // 饼图半径
  center?: string[] | number[]; // 饼图中心点
  showLegend?: boolean; // 是否显示图例
  colorPalette?: string[]; // 自定义颜色
  className?: string;
  loading?: boolean;
  errorMessage?: string;
  emptyDataMessage?: string;
  labelFormatter?: string | ((params: any) => string); // 标签格式化
}

/**
 * 饼图/环形图组件
 */
const PieChart: React.FC<PieChartProps> = ({
  title,
  data,
  height = '400px',
  doughnut = false,
  radius = doughnut ? ['40%', '70%'] : '70%',
  center = ['50%', '50%'],
  showLegend = true,
  colorPalette,
  className,
  loading = false,
  errorMessage,
  emptyDataMessage,
  labelFormatter = '{b}: {c} ({d}%)'
}) => {
  const chartOption = useMemo<EChartsOption>(() => {
    return {
      title: title ? {
        text: title,
        left: 'center'
      } : undefined,
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: showLegend ? {
        orient: 'horizontal',
        bottom: 10,
        data: data.map(item => item.name)
      } : undefined,
      color: colorPalette,
      series: [
        {
          name: title || '数据分布',
          type: 'pie',
          radius: radius,
          center: center,
          avoidLabelOverlap: true,
          itemStyle: {
            borderRadius: 4,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: true,
            formatter: labelFormatter
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '16',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: true
          },
          data: data
        }
      ]
    };
  }, [title, data, radius, center, showLegend, colorPalette, labelFormatter]);

  // 检查数据是否为空或无效
  const hasValidData = data && data.length > 0 && data.some(item => item.value > 0);

  return (
    <EChartBase
      option={chartOption}
      style={{ height, width: '100%' }}
      className={className}
      loading={loading}
      errorMessage={errorMessage}
      emptyDataMessage={emptyDataMessage || '暂无饼图数据'}
      shouldRenderChart={() => hasValidData}
    />
  );
};

export default PieChart; 